package com.traffic.between.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.opendata.api.ODPRequest;
import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.MD5Util;

import net.sf.json.JSONObject;

public class HaiHangServiceImpl {
	private static Logger logger = Logger.getLogger(HaiHangServiceImpl.class);
	public static HaiHangServiceImpl service = new HaiHangServiceImpl();

	private static String HOST_ORDER_PATH = BetweenProperties.HNHH_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.HNHH_ORDERSTATUS_URL;
	private static String HNHH_APPKEY = BetweenProperties.HNHH_APPKEY;
	private static String HNHH_SECURITYKEY = BetweenProperties.HNHH_SECURITYKEY;

	public String order(String productId, String phoneNo, String cstmOrderNo) {
		logger.info("between- 海航订购请求参数: params productId = " + productId + ", phoneNo = " + phoneNo
				+ ", cstmOrderNo = " + cstmOrderNo);

		String response="";
		try{
		Gson gson = new Gson();
        Map<String, Object> mapInfo = new HashMap<String, Object>();
        Map<String, Object> headerMap = new HashMap<String, Object>();
        
        UUID uuid = UUID.randomUUID();
        headerMap.put("version", "1.0");
        headerMap.put("appId", uuid);
        headerMap.put("securityKey", "1");

        mapInfo.put("header", headerMap);

        Map<String, Object> bodyMap = new HashMap<String, Object>();
        bodyMap.put("operationCode", "0");
        bodyMap.put("channelCode","11"); 
        bodyMap.put("requestAmount", "1");
        bodyMap.put("payMone", "5");//支付方式（1：支付宝  2：微信 3：银联 4：话费宝 5：其他）
        bodyMap.put("ofrId", productId);
        bodyMap.put("orderNumber",cstmOrderNo);
        bodyMap.put("rcgMobile", phoneNo);
        bodyMap.put("hpno",HNHH_APPKEY);
        bodyMap.put("pin", "123456");
        bodyMap.put("destAttr", "2");

        mapInfo.put("body", bodyMap);

        //时间戳，格式为yyyy-MM-dd HH:mm:ss，时区为GMT+8。服务端允许客户端请求最大时间误差为10分钟
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = simpleDateFormat.format(new Date());


        ODPRequest odpRequest = new ODPRequest(HOST_ORDER_PATH, HNHH_SECURITYKEY);
        //方式一
        odpRequest.addTextSysPara("Method", "capability-package_recharge_recharge");
        odpRequest.addTextSysPara("AccessToken", "CFE0141AF096ACC1CD89287A99B729188F7E18BA");
        odpRequest.addTextSysPara("Timestamp",timestamp);
        odpRequest.addTextSysPara("Format", "json");

        odpRequest.addTextAppParaJson(gson.toJson(mapInfo));

        response = odpRequest.post();
        
        logger.info("between- 海航流量订购请求响应:  " + response);
        
        JSONObject resultJson = JSONObject.fromObject(response);
		JSONObject json = (JSONObject) resultJson.get("msgResponse");
		
		JSONObject responseInfo = (JSONObject) json.get("responseInfo");
		JSONObject data = (JSONObject) json.get("data");
		String resultCode = (String) data.get("ResultCode");
		String result=(String) responseInfo.get("result");
		
			if ("1".equals(result) && "0".equals(resultCode)) {
				response = "{\"resultCode\": \"00\",\"resultDesc\":\"订购中\"}";
			} else {
				response = "{\"resultCode\": \"01\",\"resultDesc\":\"充值失败\"}";
			}
	    } catch (Exception e) {  
	        logger.error("between- 海航流量订购请求时的响应异常: " + e);
	    }
			return response;
	}

	public String orderStatus(String cstmOrderNo) {
		// 自己封装请求海航云接口
		// 参考文档地址https://data.hnagroup.com/indexPage/toDocument.do?uuid=42AA5A64B424DAC435A592BFEAB3EF2D
		String respResult = "";
		try {

			String appSecret = HNHH_SECURITYKEY;
			String appToken = "CFE0141AF096ACC1CD89287A99B729188F7E18BA";
			String method = "capability-package_recharge_queryOrderInfo";
			String timestamp = "";
			String format = "json";
			StringBuffer source = new StringBuffer();

			String sign = "";

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
			Date now = new Date();
			timestamp = sdf.format(now);

			// JSONObject appJson = new JSONObject();
			JSONObject header = new JSONObject();
			JSONObject body = new JSONObject();
			// 封装应用请求头
			header.put("version", "1.0");
			header.put("appId", "1");
			header.put("securityKey", "1");
			// 封装应用请求包体
			body.put("hpno", HNHH_APPKEY);
			body.put("orderNumber", cstmOrderNo);
			System.out.println(body.toString());
			source.append(appSecret).append("AccessToken" + appToken).append("Format" + format)
					.append("Method" + method).append("Parameter" + body.toString()).append("Timestamp" + timestamp)
					.append(appSecret);
			sign = MD5Util.MD5(source.toString()); // MD5加密

			HttpPost httpRequst = new HttpPost(HOST_ORDERSTATUS_PATH);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("Method", method));
			nvps.add(new BasicNameValuePair("AccessToken", appToken));
			nvps.add(new BasicNameValuePair("Sign", sign));
			nvps.add(new BasicNameValuePair("Timestamp", timestamp));
			nvps.add(new BasicNameValuePair("Format", format));
			nvps.add(new BasicNameValuePair("Parameter", body.toString()));

			httpRequst.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			System.out.println("url=" + httpRequst.getURI());
			CloseableHttpClient httpclient = HttpClientBuilder.create().build();
			HttpResponse httpResponse = httpclient.execute(httpRequst);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity httpEntity = httpResponse.getEntity();
				respResult = EntityUtils.toString(httpEntity);// 取出应答字符串
			}
			System.out.println("result=" + respResult);
			JSONObject resultJson = JSONObject.fromObject(respResult);
			JSONObject msgResponse = (JSONObject) resultJson.get("msgResponse");

			JSONObject responseInfo = (JSONObject) msgResponse.get("responseInfo");
			JSONObject data = (JSONObject) msgResponse.get("data");
			JSONObject ORDER_ITEM = (JSONObject) data.get("ORDER_ITEM");
			String STAT_CODE = (String)ORDER_ITEM.get("STAT_CODE");// 订单状态标记
			String ResultCode = (String) data.get("ResultCode");
			String ResultDesc = (String) data.get("ResultDesc");
			String result = (String) responseInfo.get("result");
			// -1：初始状态，0：充值成功，1充值失败，2：充值中，3：手工充值成功
			if ("1".equals(result) && "0".equals(ResultCode)) {
				if ("0".equals(STAT_CODE) || "3".equals(STAT_CODE)) {
					respResult = "{\"resultCode\": \"00\",\"resultDesc\":\"充值成功\"}";
				} else if ("1".equals(STAT_CODE)) {
					respResult = "{\"resultCode\": \"01\",\"resultDesc\":\"" + ResultDesc + "\"}";
				} else {
					respResult = "{\"resultCode\": \"02\",\"resultDesc\":\"" + ResultDesc + "\"}";
				}
			} else {
				respResult = "{\"resultCode\": \"01\",\"resultDesc\":\"" + ResultDesc + "\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "{\"resultCode\": \"01\",\"resultDesc\":\"" + "系统异常" + e.getMessage() + "\"}";
		}
		return respResult;

	}
}
